// 对数据点进行时间排序
const sortedPoints = predictionPoints.sort((a, b) => {
  const timeA = a.timestamp.split(":").map(Number);
  const timeB = b.timestamp.split(":").map(Number);
  return timeA[0] * 60 + timeA[1] - (timeB[0] * 60 + timeB[1]);
});

// 初始化图表
document.addEventListener("DOMContentLoaded", function () {
  const ctx = document.getElementById("trendChart").getContext("2d");

  // 苹果风格的颜色
  const colors = {
    blue: "#0071e3",
    lightBlue: "#42a1ec",
    green: "#34c759",
    red: "#ff3b30",
    yellow: "#ffcc00",
    purple: "#5e5ce6",
    gray: "#8e8e93",
  };

  // 创建主数据集
  const mainDataset = {
    label: "预测",
    data: sortedPoints.map((p) => ({
      x: p.timestamp,
      y: p.value,
    })),
    borderColor: colors.blue,
    backgroundColor: "rgba(0, 113, 227, 0.05)",
    borderWidth: 2,
    pointRadius: (context) => {
      const point = sortedPoints[context.dataIndex];
      return point?.is_future ? 0 : 0.5;
    },
    pointHoverRadius: 3,
    pointBackgroundColor: "#ffffff",
    pointBorderColor: colors.blue,
    pointBorderWidth: 1,
    fill: true,
    tension: 0.3,
    segment: {
      borderDash: (context) => {
        const index = context.p0DataIndex;
        const currentPoint = sortedPoints[index];
        return currentPoint?.is_future ? [3, 3] : undefined;
      },
    },
  };

  // 昨日数据集 - 默认显示
  const yesterdayDataset = {
    label: "昨日",
    data: yesterdayPoints.map((p) => ({
      x: p.timestamp,
      y: p.value,
    })),
    borderColor: colors.purple,
    backgroundColor: "rgba(94, 92, 230, 0)",
    borderWidth: 1.5,
    borderDash: [3, 3],
    tension: 0.3,
    fill: false,
    pointRadius: 0,
    pointHoverRadius: 3,
    hidden: false, // 默认显示
  };

  window.trendChart = new Chart(ctx, {
    type: "line",
    data: {
      datasets: [
        // 目标值
        {
          label: "目标",
          data: Array(sortedPoints.length)
            .fill({
              x: sortedPoints[0]?.timestamp,
              y: targetValue,
            })
            .concat(
              Array(sortedPoints.length).fill({
                x: sortedPoints[sortedPoints.length - 1]?.timestamp,
                y: targetValue,
              })
            ),
          borderColor: colors.yellow,
          backgroundColor: "rgba(255, 204, 0, 0)",
          borderWidth: 1.5,
          borderDash: [3, 5],
          fill: false,
          pointRadius: 0,
          pointHoverRadius: 0,
        },
        // 预警线（近7日日均流水）
        {
          label: "日均",
          data: Array(sortedPoints.length)
            .fill({
              x: sortedPoints[0]?.timestamp,
              y: warningValue,
            })
            .concat(
              Array(sortedPoints.length).fill({
                x: sortedPoints[sortedPoints.length - 1]?.timestamp,
                y: warningValue,
              })
            ),
          borderColor: colors.red,
          backgroundColor: "rgba(255, 59, 48, 0)",
          borderWidth: 1.5,
          borderDash: [3, 5],
          fill: false,
          pointRadius: 0,
          pointHoverRadius: 0,
        },
        mainDataset,
        yesterdayDataset,
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        mode: "index",
        intersect: false,
      },
      onHover: function (event, activeElements, chart) {
        // 只有在鼠标悬停在数据点上时才显示tooltip
        chart.options.plugins.tooltip.enabled = activeElements.length > 0;
        chart.update("none");
      },
      animation: {
        duration: 1000,
        easing: "easeOutQuart",
      },
      plugins: {
        legend: {
          display: true,
          position: "top",
          align: "end",
          labels: {
            boxWidth: 3,
            boxHeight: 3,
            usePointStyle: true,
            pointStyle: "circle",
            padding: 15,
            color: "#1d1d1f",
            font: {
              family:
                "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
              size: 12,
              weight: "500",
            },
            filter: function (legendItem, data) {
              // 隐藏预测线的图例
              return legendItem.text !== "预测";
            },
          },
          onClick: function (e, legendItem, legend) {
            // 保留图例点击切换功能
            const index = legendItem.datasetIndex;
            const ci = legend.chart;
            ci.data.datasets[index].hidden = !ci.data.datasets[index].hidden;
            ci.update();
          },
        },
        tooltip: {
          backgroundColor: "rgba(255, 255, 255, 0.95)",
          titleColor: "#1d1d1f",
          bodyColor: "#1d1d1f",
          borderColor: "rgba(0, 0, 0, 0.1)",
          borderWidth: 1,
          cornerRadius: 8,
          padding: 12,
          boxPadding: 6,
          usePointStyle: true,
          titleFont: {
            family:
              "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
            size: 13,
            weight: "600",
          },
          bodyFont: {
            family:
              "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
            size: 12,
          },
          callbacks: {
            label: function (context) {
              let label = context.dataset.label || "";
              if (label) {
                label += ": ";
              }
              if (context.parsed.y !== null) {
                label += new Intl.NumberFormat("zh-CN", {
                  style: "currency",
                  currency: "CNY",
                  minimumFractionDigits: 0,
                  maximumFractionDigits: 0,
                }).format(context.parsed.y);
              }
              return label;
            },
          },
        },
      },
      scales: {
        x: {
          type: "time",
          time: {
            parser: "HH:mm",
            unit: "hour",
            displayFormats: {
              hour: "HH:mm",
            },
            tooltipFormat: "HH:mm",
          },
          grid: {
            display: true,
            color: "rgba(0, 0, 0, 0.05)",
            drawBorder: false,
          },
          ticks: {
            color: "#8e8e93",
            font: {
              family:
                "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
              size: 11,
            },
            maxTicksLimit: 8,
            maxRotation: 0,
          },
          border: {
            display: false,
          },
        },
        y: {
          grid: {
            color: "rgba(0, 0, 0, 0.05)",
            drawBorder: false,
          },
          min: chartBounds.min,
          max: chartBounds.max,
          border: {
            display: false,
          },
          ticks: {
            color: "#8e8e93",
            font: {
              family:
                "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
              size: 11,
            },
            callback: function (value) {
              return Math.round(value / 10000) + "万";
            },
          },
        },
      },
    },
  });
});
